import { Image ,Divider, List, Skeleton, Tabs ,Button, Tooltip ,Avatar,notification} from 'antd';
import { ToTopOutlined , PlayCircleOutlined , BorderInnerOutlined , PlusSquareOutlined , HeartOutlined , CloseOutlined ,  MessageOutlined , UnorderedListOutlined ,HeartTwoTone} from '@ant-design/icons';
import {getRecommendList , getRecommendListItem , getRecommendMusicList ,getPlaylistreviews , getSubscribers , pushComment,likeComment ,likeMusic} from '../../api/recommend'
import { useEffect, useRef, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import {getSongDetail,getSongUrl,getLyric} from '../../api/details.js'
import { formData } from './util';
import { useDispatch } from 'react-redux';
import { setSongInfo } from "@/store/modules/songInfo";
const ApRecommendDay= () => {
  const [data, setData] = useState([]);
  const [musicList,setMusicList] = useState({})
  const [songList,setSongList] = useState([])
  // 显示详情
  const [ifshow,setIfshow] = useState(false)
  // 获取每日推荐歌单列表
  const getList = () =>{
    getRecommendList().then((res) =>{
      setData([...res.data.result])
    })
  }
  // 获取歌单详情
  const getRecItem = (id) =>{
    getRecommendListItem(id).then((res) =>{
      setMusicList({...res.data.playlist})
    })
  }
  // 获取全部曲目
  const getMusicList = (id) =>{
    getRecommendMusicList(id).then((res) =>{
      setSongList([...res.data.songs])
      console.log(res.data.songs)
    })
  }
  // 获取歌单全部信息
  const getAll = (id) =>{
    getMusicList(id)
    getRecItem(id)
    setIfshow(!ifshow)
  }
  // 更改窗口显示
  const changeBox = () =>{
    setIfshow(!ifshow)
  }
  useEffect(() => {
    getList();
  }, []);
  return (
    <div>
      {
        ifshow ? <div><Item data = {musicList} change = {changeBox} songList = {songList}></Item></div> : null
      }
      <div
      id="scrollableDiv"
      style={{
        height: 700,
        overflow: 'auto',
        padding: '25px',
        border: '1px solid rgba(140, 140, 140, 0.35)',
      }}
    >
      <InfiniteScroll
        dataLength={data.length}
        hasMore={data.length < 50}
        loader={
          <Skeleton
            avatar
            paragraph={{
              rows: 1,
            }}
            active
          />
        }
        endMessage={<Divider plain>没有更多啦~ 🤐</Divider>}
        scrollableTarget="scrollableDiv"
      >
        <List
          dataSource={data}
          renderItem={(item) => (
            <List.Item key={item.id}>
            <Image
              width={100}
              src={item.picUrl}
            />
              <List.Item.Meta
                title={<p className='songName' style={{marginLeft:'25px' ,cursor:'pointer' , fontSize:'18px'}} onClick={() =>{getAll(item.id)}}>{item.name}</p>}
                description={<p style={{marginLeft:'25px',marginTop:'15px'}}>更新时间:{formData(item.trackNumberUpdateTime)}</p>}
              />
              <div><p style={
                {color:'rgb(106, 112, 117)'}
              }>{item.playCount}次播放</p>
              </div>
            </List.Item>
          )}
        />
      </InfiniteScroll>
    </div>
    </div>
  );
};

const Item = (props) =>{
  // 储存评论状态
  const[reviews,setReviews] = useState([])
  // 储存歌单收藏者状态
  const[subscribers,setSubscribers] = useState([]) 
  const [data, setData] = useState([]);
  const dispatch = useDispatch()
  const [api, contextHolder] = notification.useNotification();
  const openNotificationWithIcon = (type) => {
    api[type]({
      message: '评论成功！！',
      description:
        '因网络原因可能稍后显示哦',
    });
  };
  const openNotificationWithIcon2 = (type) => {
    api[type]({
      message: '已添加到我喜欢的音乐',
      description:
        '因网络原因可能稍后显示哦',
    });
  };
  const comRef = useRef()
  const urlRef = useRef()
  const lrcRef = useRef()
  const clickTest =  async (id) =>{
    await getSongUrl({id , level: "standard"}).then(res =>{
      urlRef.current = res?.data?.data?.[0].url;
      getLyric({id}).then(res =>{
        lrcRef.current = res?.data?.lrc?.lyric;
      })
      getSongDetail({ids:id}).then(res =>{
        dispatch(
          setSongInfo({
            // 歌名
            name: res?.data?.songs?.[0]?.al?.name,
            // 封面
            cover: res?.data?.songs?.[0]?.al?.picUrl,
            // 作者
            artist: res?.data?.songs?.[0]?.ar
              .map((item) => {
                return item?.name;
              })
              .join(","),
            url: urlRef.current,
            lrc: lrcRef.current,
          })
        )
      })
    })
  }
  // 发表评论
  const pushcomments = () =>{
    pushComment({t:1,type:2,content:comRef.current.value,id:props.data.id}).then(res =>{
      getPlaylistreviews(props.data.id).then(res =>{
        setReviews([...res.data.data.comments])
      })
      console.log(res)
      comRef.current.value=''
      openNotificationWithIcon('success')
    })
  }
  // 给评论点赞
  const commentPop = (id,flag) =>{
    if(flag){
      likeComment({id:props.data.id,cid:id,t:0,type:2}).then(res =>{
        getPlaylistreviews(props.data.id).then(res =>{
          setReviews([...res.data.data.comments])
        })
      })
      return
    }else{
      likeComment({id:props.data.id,cid:id,t:1,type:2}).then(res =>{
        getPlaylistreviews(props.data.id).then(res =>{
          setReviews([...res.data.data.comments])
        })
      })
    }
  }
  // 喜欢音乐
  const musicPop = (id) =>{
    likeMusic({id}).then(res =>{
      console.log(res)
      openNotificationWithIcon2('success')
    })
  }
  useEffect(() =>{
    setData([...props.songList])
  },[props])
  const onChange = (key) => {
    if(key === '2'){
      getPlaylistreviews(props.data.id).then(res =>{
        setReviews([...res.data.data.comments])
      })
    }
    if(key === '3'){
      getSubscribers(props.data.id).then(res =>{
        setSubscribers([...res.data.subscribers])
      })
    }
  };
  const items = [
    {
      key: '1',
      label: `歌曲列表`,
      children: <div>
      <div
      id="scrollableDiv"
      style={{
        height: 290,
        overflow: 'auto',
      }}
    >
     {contextHolder}
      <InfiniteScroll
        dataLength={data.length}
        hasMore={data.length < 100}
        loader={
          <Skeleton
            avatar
            paragraph={{
              rows: 1,
            }}
            active
          />
        }
        endMessage={<Divider plain><p style={{color:' rgb(162, 162, 162)' , fontSize:'8px'}}>————加载完毕————</p></Divider>}
        scrollableTarget="scrollableDiv"
      >
        <List
          dataSource={data}
          renderItem={(item) => (
            <List.Item key={item.email}>
            <div style={{marginRight:'6px'}}>
            <Image
              width={50}
              src={item.al.picUrl}
            />
            </div>
              <List.Item.Meta
                title={<p onClick={() =>{clickTest(item.id)}} className='songName' style={{cursor:'pointer'}}>{item.name}</p>}
                description={item.ar[0].name}
              />
              {/* 按钮 */}
              <div style={{marginRight:'6px'}}>
              <Button type="text" icon={item.resourceState ? <HeartOutlined /> : <HeartTwoTone twoToneColor="#eb2f96" />} onClick={()=>{
                item.resourceState=false
                musicPop(item.id)
                }}/>
              </div>
              <Button type="text" icon={<PlusSquareOutlined />}/>
            </List.Item>
          )}
        />
      </InfiniteScroll>
    </div>
      </div>,
    },
    {
      key: '2',
      label: `评论`,
      children: <div style={{height:'210px' , width:'880px'}}>
        <div>
          <div
        id="scrollableDiv"
        style={{
          height: 265,
          overflow: 'auto',
        }}
      >
        <InfiniteScroll
          dataLength={reviews.length}
          hasMore={reviews.length < 100}
          loader={
            <Skeleton
              avatar
              paragraph={{
                rows: 1,
              }}
              active
            />
          }
          endMessage={<Divider plain><p style={{color:' rgb(162, 162, 162)' , fontSize:'8px'}}>————加载完毕————</p></Divider>}
          scrollableTarget="scrollableDiv"
        >
          <List
            dataSource={reviews}
            renderItem={(item) => (
              <List.Item key={item.commentId}>
                <List.Item.Meta
                  avatar={<Avatar src={item.user.avatarUrl} />}
                  title={<p style={{cursor:'default'}}>{item.user.nickname} <span style={{fontSize:'10px' , color:'rgb(118, 134, 123)' , fontWeight:'3'}}>ip:{item.ipLocation.location}</span></p>}
                  description=<p>{item.content}<span style={{color:'rgb(118, 134, 123)' , fontSize:'10px'}}> {item.timeStr}</span></p>
                />
                <div><Button type="text" onClick={() =>{commentPop(item.commentId , item.liked)}} icon={item.liked ?  <HeartTwoTone twoToneColor="#eb2f96" />:<HeartOutlined />}/><Button type="text" icon={<MessageOutlined />}/></div>
              </List.Item>
            )}
          />
        </InfiniteScroll>
    </div>
    <div style={{padding:'6px'}}>
      <input type='text' ref={comRef} style={{width:'775px',height:'32px' ,marginBottom:'2px' , border:'1px solid rgb(21, 127, 54)' , borderRadius:'5px'}}></input>
      <div style={{float:'right'}}><Button type="primary" onClick={pushcomments}>发表评论</Button></div>
    </div>
        </div>
      </div>,
    },
    {
      key: '3',
      label: `收藏者`,
      children:  <div
      id="scrollableDiv"
      style={{
        height: 300,
        overflow: 'auto',
      }}
    >
      <InfiniteScroll
        dataLength={subscribers.length}
        hasMore={subscribers.length < 50}
        loader={<Skeleton avatar paragraph={{ rows: 1 }} active />}
        endMessage={<Divider plain><p style={{color:' rgb(162, 162, 162)' , fontSize:'8px'}}>————加载完毕————</p></Divider>}
        scrollableTarget="scrollableDiv"
      >
        <List
          dataSource={subscribers}
          renderItem={(item) => (
            <List.Item key={item.avatarUrl}>
              <List.Item.Meta
                avatar={<Avatar src={item.avatarUrl} />}
                title={<p style={{cursor:'default'}}>{item.nickname}</p>}
                description={ item.signature ===''? <p style={{color:'rgb(110, 110, 110)' , fontSize:'8px'}}>个人简介:null</p> : <p style={{color:'rgb(110, 110, 110)' , fontSize:'8px'}}>个人简介:{item.signature}</p>}
              />
              <div style={{marginRight:'6px'}}>
              <Button type="text" icon={<UnorderedListOutlined />}/>
              </div>
            </List.Item>
          )}
        />
      </InfiniteScroll>
    </div>,
    },
  ];
  const [tags,setTags] = useState([])
  useEffect(() =>{
    setTags([props.data.tags])
  },[props])
  return<div style={{
    height:'660px',
    width:'900px',
    background:'white',
    position:'fixed',
    top:'10%',
    left:'25%',
    zIndex:9999,
    border: '1px solid rgb(211, 209, 209)',
    padding:'10px'
  }}>
  <div style={{display:'flex'}}>
  <Image width={300} src={props.data.coverImgUrl}/>
  <div style={{marginLeft:'12px' , width:'650px'}}>
  <div style={{float:'right'}}><Button type="text" icon={<CloseOutlined />} onClick={props.change}></Button></div>
  <h1 style={{fontSize:'27px'}} >{props.data.name}</h1>
  <p>标签: {tags.map((item,index) =>{
    return<span key={index} style={{color:' rgb(21, 127, 54)' , marginTop:'12px'}}>/{item}</span>
  })}</p>
  {/* 按钮 */}
  <div style={{marginTop:'2px' , marginBottom:'40px'}}>
  <div style={{marginRight:'12px' , float:'left'}}>
  <Tooltip title="search">
    <Button type="primary" icon={<PlayCircleOutlined />}>播放全部</Button>
  </Tooltip>
  </div>
  <div style={{marginRight:'12px', float:'left'}}>
  <Tooltip title="search">
    <Button type="dashed" icon={<BorderInnerOutlined />}>收藏</Button>
  </Tooltip>
  </div>
  <div style={{marginRight:'12px', float:'left'}}>
  <Tooltip title="search">
    <Button type="dashed" icon={<ToTopOutlined />}>分享</Button>
  </Tooltip>
  </div>
  </div>
  {/* 简介 */}
  <div style={{height:'180px' , width:'600px' , overflow:'auto'}}> <p style={{color:'rgb(104, 103, 103)'}}>{props.data.description}</p></div>
  </div>
  </div>
  {/* 切换栏 */}
 <Tabs defaultActiveKey="1" items={items} onChange={onChange} centered/>
  </div>
}
export default ApRecommendDay;